package org.huangrui.juc.source.cf;

import java.util.concurrent.*;

/**
 * @Author hr
 * @Create 2024-04-01 12:13
 */
public class T07_CompletableFutureAPI {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        group2();

    }

    private static void group2() {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CompletableFuture.supplyAsync(() -> {
            // 暂停几秒钟
            try { TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
            System.out.println("111");
            return 1;
        },threadPool).handle((v,e1)->{
            int i = 10/0;
            try { TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
            System.out.println("222");
            return v + 2;
        }).handle((v,e1) ->{
            //暂停几秒钟
            try { TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
            System.out.println("333");
            return v + 3;
        }).whenComplete((v,e)->{
            if (e == null){
                System.out.println("----计算结果： "+v);
            }
        }).exceptionally(e->{
            e.printStackTrace();
            System.out.println("异常："+e.getMessage());
            return null;
        });
        System.out.println(Thread.currentThread().getName()+"----主线程先去忙其它任务");
        threadPool.shutdown();

        //1、主线程不要立刻结束，否则completableFuture默认使用的线程池会立刻关闭
        // try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { throw new RuntimeException(e); }
    }

    /**
     * 获得结果和触发计算
     *
     * @throws InterruptedException
     * @throws ExecutionException
     */
    private static void group1() throws InterruptedException, ExecutionException {
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            // 暂停几秒钟线程
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "abc";
        });

        // System.out.println(completableFuture.get());
        // System.out.println(completableFuture.get(2L,TimeUnit.SECONDS));
        // System.out.println(completableFuture.join());

        // 暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }

        System.out.println(completableFuture.getNow("xxx"));
        System.out.println(completableFuture.complete("completeValue") + "\t" + completableFuture.get());
    }
}
